package com.usefullc.english.service;

import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONPath;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jayway.jsonpath.JsonPath;
import com.usefullc.common.exception.BizException;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.common.util.http.HttpNewUtils;
import com.usefullc.common.util.http.RequestRes;
import com.usefullc.common.util.http.ResponseRes;
import com.usefullc.english.domain.UserWordDict;
import com.usefullc.english.domain.WordDict;
import com.usefullc.english.enums.WordDictTypeEnum;
import com.usefullc.english.mapper.WordDictMapper;
import com.usefullc.english.query.WordDictQuery;
import com.usefullc.english.vo.WordDictVo;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.service.AbstractBizService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.CharSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;

/**
 * 词典服务类
 * @author: 星空
 * @date: 2022-08-11
 */
@Service
public class WordDictService extends AbstractBizService<WordDictMapper, WordDict, WordDictQuery> {

    @Autowired
    private UserWordDictService userWordDictService;

    @Override
    protected QueryWrapper<WordDict> getQueryWrapper(WordDictQuery query) {
        QueryWrapper<WordDict> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    public Pager<WordDictVo> findVoByPage(WordDictQuery query){
        Pager<WordDict> page = this.findByPage(query);
        Pager<WordDictVo> newPage = new Pager<>(page);
        List<WordDict> dataList = page.getDataList();
        List<WordDictVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (WordDict wordDict : dataList) {
            WordDictVo wordDictVo = BeanUtils.beanCopy(wordDict, WordDictVo.class);
            newDataList.add(wordDictVo);
        }
        return newPage;
    }

    public WordDictVo findByName(String name){
        //原型,查询的name 不区分大小写
        WordDictQuery wordDictQuery = new WordDictQuery();
        wordDictQuery.setName(name);
        WordDict wordDict = this.findOne(wordDictQuery);
        if(wordDict == null){
            return null;
        }
//        //换成小写
//        name = name.toLowerCase();
//        wordDictQuery = new WordDictQuery();
//        wordDictQuery.setName(name);
//        wordDict = this.findOne(wordDictQuery);
//        if(wordDict == null){
//            return null;
//        }

        WordDictVo wordDictVo = BeanUtils.beanCopy(wordDict, WordDictVo.class);

        //
        Map<String,String> wordFeatureMap = new LinkedHashMap<>();
        if (StringUtils.isNotEmpty(wordDictVo.getNoun())) {
            wordFeatureMap.put("noun",wordDictVo.getNoun());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getPron())) {
            wordFeatureMap.put("pron",wordDictVo.getPron());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getAdj())) {
            wordFeatureMap.put("adj",wordDictVo.getAdj());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getAdv())) {
            wordFeatureMap.put("adv",wordDictVo.getAdv());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getVerb())) {
            wordFeatureMap.put("verb",wordDictVo.getVerb());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getNum())) {
            wordFeatureMap.put("num",wordDictVo.getNum());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getArt())) {
            wordFeatureMap.put("art",wordDictVo.getArt());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getPrep())) {
            wordFeatureMap.put("prep",wordDictVo.getPrep());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getConj())) {
            wordFeatureMap.put("conj",wordDictVo.getConj());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getInterj())) {
            wordFeatureMap.put("interj",wordDictVo.getInterj());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getAbbr())) {
            wordFeatureMap.put("interj",wordDictVo.getAbbr());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getAux())) {
            wordFeatureMap.put("aux",wordDictVo.getAux());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getDet())) {
            wordFeatureMap.put("det",wordDictVo.getDet());
        }
        if (StringUtils.isNotEmpty(wordDictVo.getOtherComment())) {
            wordFeatureMap.put("other",wordDictVo.getOtherComment());
        }
        wordDictVo.setWordFeatureMap(wordFeatureMap);

//        boolean structureChange = false;
//        if(StringUtils.isNotEmpty(wordDictVo.getNounPlural())
//                || StringUtils.isNotEmpty(wordDictVo.getNounPlural()))

//        List<String> wordTenseList = new ArrayList<>();
//        if (StringUtils.isNotEmpty(wordDictVo.getThirdSingle())) {
//            wordTenseList.add(wordDictVo.getNounPlural());
//            wordTenseList.add(wordDictVo.getThirdSingle());
//            wordTenseList.add(wordDictVo.getParticiple());
//            wordTenseList.add(wordDictVo.getPastTense());
//            wordTenseList.add(wordDictVo.getPastParticiple());
//            wordDictVo.setWordFeatureMap(wordFeatureMap);
//        }

        //
        String levelTags = wordDictVo.getLevelTags();
        if (StringUtils.isNotEmpty(levelTags)) {
            String[] tags = levelTags.split(",");
            List<String> levels = Arrays.asList(tags);
            wordDictVo.setLevels(levels);
        }
        return wordDictVo;

    }

    public WordDictVo findByNameOrBuild(String name){
        WordDictVo wordDict = this.findByName(name);
        if(wordDict == null){
            //集群场景，考虑分布式锁 todo
            synchronized (name){
                buildByYoudao(name);
            }
        }
        wordDict = this.findByName(name);
        return wordDict;
    }
    private String prevWord = "what";

    public WordDictVo buildByYoudao(String name){
        //请求获取数据
        String url = "https://dict.youdao.com/jsonapi_s?doctype=json&jsonversion=4";
        RequestRes requestRes = new RequestRes();
        requestRes.setMethod("POST");
        requestRes.setUrl(url);
        Map<String,Object> paramsMap = new HashMap<>();
//        try {
//            String qname = URLEncoder.encode(name, Charset.defaultCharset().toString());
//            paramsMap.put("q", qname);
//        } catch (UnsupportedEncodingException e) {
//            throw new BizException("操作失败",e);
//        }
        paramsMap.put("q", name);
        paramsMap.put("le","en");
        paramsMap.put("t",1);
        paramsMap.put("client","web");
        paramsMap.put("sign","867586581c27d3a74eef1daae5ee8fbe");
        paramsMap.put("keyfrom","webdict");
        requestRes.setParams(paramsMap);

        requestRes.addHeader("Referer","https://dict.youdao.com/result?word="+prevWord+"&lang=en");
        prevWord = name;
        requestRes.addHeader("Origin","https://dict.youdao.com/");
        requestRes.addHeader("Host","dict.youdao.com");
        requestRes.addHeader("Content-Type","application/x-www-form-urlencoded");
        requestRes.addHeader("Cookie","OUTFOX_SEARCH_USER_ID_NCOO=1150411531.986487; OUTFOX_SEARCH_USER_ID=\"-521889429@10.110.96.158\"; NTES_YD_SESS=6Gd0aY7M2Z078keQPZJ9wEnyuwqzlptrmEDu07XPzzqNVQXFV_orx5_qT0bn1LC94IK_C1JOt84XKaB1wRTjoLsYQfo8kpzWYOh6uQ6uze53h2CH7wcVPPtN1j9Htg8S_6oFbwcCzxb53gVOnfHrLxS8nwnhLOCjMXRqFUIO1FVbFz2UENd9fiUYRYuWPokzH0fLZRIb6Nl1kdiFLYhmACsd3jt5O_BubLsZ6.tns8DvM; NTES_YD_PASSPORT=N.gqVz2uBgPNWIoxk6qBN9LDyZ6BbDTCmonjirFn8.Du_q13_H8IY.HgwAOJlmNSzKuHNl0BGdz9wP1ulH4h0RK2DgWGSM_knCAALPIek.GKSvX6KKd06yhV1V3WPlMo3sSNy03ENLFFuc324n97m7Qsz1hmc3gQDwtt4kua3K9BFe9j4q_HWc4kYz64Dg_gGmS6..FUXKlcpiICjY2NnFnmWtv35MaEm; S_INFO=1660389898|0|0&60##|15267164682; P_INFO=15267164682|1660389898|1|dict_logon|00&99|null&null&null#CN&null#10#0|&0||15267164682; DICT_SESS=v2|tLxdJaAW2RYl6MlGRfpK0QL0Ml5RfgF0zfRfOYhfO50wZ0f6yhLPy0k5n4wZO4wFROYOMeKhL6B0Puk4lGRMpB0UGkMPz0HJK0; DICT_PERS=v2|urs-phone-web||DICT||web||604800000||1660389898717||36.157.163.47||urs-phoneyd.f3447f6616e5490fa@163.com||Y5nf6unLkWRQz0LeLkfw4RzfhfTuRfUA0TBnLQy6LUf06BPMpLOLkG0U56LlMhM6B0PBnLeFOLwBRQLOfpLkLzm0; DICT_LOGIN=3||1660389898726; ___rl__test__cookies=1660392712373");
        ResponseRes responseRes = HttpNewUtils.execute(requestRes);
        String bodyText = responseRes.getBodyText();
        List<LinkedHashMap<String,String>> trsList = new ArrayList<>();
        try{
            trsList = JsonPath.read(bodyText, "$.ec.word.trs");
        }catch (Exception e){
        }

        if(CollectionUtils.isEmpty(trsList)){
            throw new BizException("没有您要找的单词 "+name,false);
        }

        List<LinkedHashMap<String,Map<String,String>>> tfsList = new ArrayList<>();
        try{
            tfsList = JsonPath.read(bodyText, "$.ec.word.wfs");
        }catch (Exception e){
        }

        List<String> levelTags = new ArrayList<>();
        try{
            levelTags = JsonPath.read(bodyText, "$.ec.exam_type");
        }catch (Exception e){
        }
        String ukphone = "unknown";
        String usphone = "unknown";
        try{
            ukphone = JsonPath.read(bodyText, "$.ec.word.ukphone");
            usphone = JsonPath.read(bodyText, "$.ec.word.usphone");
            name = JsonPath.read(bodyText, "$.ec.word.return-phrase");
        }catch (Exception e){
        }

        WordDict wordDict = new WordDict();
        wordDict.setName(name);
        Integer type = WordDictTypeEnum.WORD.getCode();
        if(name.split("\\s+").length > 1){
            type = WordDictTypeEnum.PHRASE.getCode();
        }
        wordDict.setType(type);
        wordDict.setUsPhoneticSymbol(usphone);
        wordDict.setUkPhoneticSymbol(ukphone);
//        wordDict.setUsPronunciation();
//        wordDict.setUkPronunciation();
        wordDict.setLevelTags(StringUtils.join(levelTags,","));
        if (CollectionUtils.isNotEmpty(trsList)) {
            for (LinkedHashMap<String, String> map : trsList) {
                if(!map.containsKey("pos")){
                    String tran = map.get("tran");
                    wordDict.setOtherComment(tran);
                    continue;
                }
                if(map.get("pos").equalsIgnoreCase("n.")){
                    if(wordDict.getNoun() != null){
                        wordDict.setNoun(wordDict.getNoun()+" "+map.get("tran"));
                    }else{
                        wordDict.setNoun(map.get("tran"));
                    }
                }else if(map.get("pos").equalsIgnoreCase("v.")){
                    wordDict.setVerb(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("pron.")){
                    wordDict.setPron(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("adj.")){
                    wordDict.setAdj(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("adv.")){
                    wordDict.setAdv(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("num.")){
                    wordDict.setNum(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("art.")){
                    wordDict.setArt(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("prep.")){
                    wordDict.setPrep(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("conj.")){
                    wordDict.setConj(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("int.")){
                    wordDict.setInterj(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("abbr.") || map.get("pos").equalsIgnoreCase("contr.")){
                    wordDict.setAbbr(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("aux.")){
                    wordDict.setAux(map.get("tran"));
                }else if(map.get("pos").equalsIgnoreCase("det.")){
                    wordDict.setDet(map.get("tran"));
                }else{
                   logger.warn(map.toString());
                }
            }
        }

        if(CollectionUtils.isNotEmpty(tfsList)){
            for (LinkedHashMap<String, Map<String, String>> map : tfsList) {
                if (map.get("wf").get("name").equalsIgnoreCase("复数")) {
                    wordDict.setNounPlural(map.get("wf").get("value"));
                }else if (map.get("wf").get("name").equalsIgnoreCase("第三人称单数")) {
                    wordDict.setThirdSingle(map.get("wf").get("value"));
                }else if (map.get("wf").get("name").equalsIgnoreCase("现在分词")) {
                    wordDict.setParticiple(map.get("wf").get("value"));
                }else if (map.get("wf").get("name").equalsIgnoreCase("过去式")) {
                    wordDict.setPastTense(map.get("wf").get("value"));
                }else if (map.get("wf").get("name").equalsIgnoreCase("过去分词")) {
                    wordDict.setPastParticiple(map.get("wf").get("value"));
                }else if (map.get("wf").get("name").equalsIgnoreCase("比较级")) {
                    wordDict.setComparative(map.get("wf").get("value"));
                }else if (map.get("wf").get("name").equalsIgnoreCase("最高级")) {
                    wordDict.setSuperlative(map.get("wf").get("value"));
                }
            }
        }

        WordDictVo oldBean = this.findByName(name);
        if(oldBean != null){
            wordDict.setId(oldBean.getId());
            this.update(wordDict);
        }else{
            this.save(wordDict);
        }
        WordDictVo wordDictVo = BeanUtils.beanCopy(wordDict, WordDictVo.class);
        return wordDictVo;

    }


}
